<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Mail;

class UsersController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth',[
           'except' => ['show','create','store','index','confirm']
        ]);
    }
    public function create()
    {
        return view('users.create');
    }

    public function index()
    {
        $users=User::paginate(10);
        return view('users.index',compact('users'));
    }

    public function show(User $user)
    {

        $blogs=$user->feed()->paginate(10);

        return view('users.show',compact('user','blogs'));
    }

    public function store(Request $request)
    {
        $this->validate($request,[
            'name' => 'required',
            'email' => 'required|email|unique:users',
            'password' => 'required|confirmed'
        ]);
        $user=User::create([
           'name' => $request->name,
           'email' => $request->email,
           'password' => bcrypt($request->password)
        ]);
        $this->sendEmail($user);
        session()->flash('success','已发送邮件，请注意查收！');
        return back();
    }

    public function edit(User $user)
    {
        $this->authorize('update',$user);
        return view('users.edit',compact('user'));
    }

    public function update(Request $request,User $user)
    {
        $this->validate($request,[
            'name' => 'required',
            'password' => 'confirmed',
        ]);
        if($request->password){
            $data=['name' => $request->name,'password' => $request->password];
        }else{
            $data=['name' => $request->name];
        }
        $user->update($data);
        session()->flash('success','更新成功！');
        return redirect()->route('users.show',Auth::user());
    }

    public function destroy(User $user)
    {
        $this->authorize('destroy',$user);
        $user->delete();
        session()->flash('success','删除成功!');
        return back();
    }

    public function confirm($token)
    {
        $user=User::where('token',$token)->firstOrFail();

        $user->token=null;
        $user->status=1;
        $user->save();

        Auth::login($user);
        session()->flash('success','激活成功！');
        return redirect()->route('users.show',[$user]);

    }

    public function sendEmail($user)
    {
        $view='emails.confirm';
        $data=compact('user');
        $from='1@qq.com';
        $name='1';
        $to=$user->email;
        $subject="邮件已经发送，请注意查收";

        Mail::send($view,$data,function($message) use ($from,$name,$to,$subject){
           $message->from($from,$name)->to($to)->subject($subject);
        });
    }
}
